#include "TileLayer.h"
#include "Game.h"

TileLayer::TileLayer(int tileSize,
                     const std::vector<Tileset> &tilesets)
    :m_position(0,0),
    m_velocity(0,0),
    m_tilesets(tilesets),
    m_tileSize(tileSize)
{
    m_numColumns = (TheGame::Instance()->getGameWidth()/m_tileSize);
    m_numRows = (TheGame::Instance()->getGameHeight()/m_tileSize);
}

void TileLayer::update(){
    m_position += m_velocity;
    m_velocity.setX(1);
}

void TileLayer::render(){
    int x, y;
    int x2, y2 = 0;

    x = m_position.getX() / m_tileSize;
    y = m_position.getY() / m_tileSize;

    x2 = int(m_position.getX()) % m_tileSize;
    y2 = int(m_position.getY()) % m_tileSize;
#if 0
    int id = 1;
    Tileset tileset = getTilesetByID(id);
    //std::cout << "tileset name:" << tileset.name
    //          << ",tile size:" << m_tileSize << std::endl;
    TheTextureManager::Instance()->drawTile(
                tileset.name,
                2,2,
                0, 0,
                m_tileSize, m_tileSize,
                0,
                0,
                TheGame::Instance()->getRenderer()
                    );
#endif
#if 1
    for (int i = 0; i < m_numRows; i++){
        for (int j = 0; j < m_numColumns; j++){
            int id = m_tileIDs[i][j + x];
            if (id == 0){
                continue;
            }
            Tileset tileset = getTilesetByID(id);
            id--;//[by jim] ??
            
            TheTextureManager::Instance()->drawTile(
                tileset.name,
                2,2,
                (j * m_tileSize) - x2, (i * m_tileSize) - y2,
                m_tileSize, m_tileSize,
                (id - (tileset.firstGridID -1)) / tileset.numColumns,
                (id - (tileset.firstGridID -1)) % tileset.numColumns,
                TheGame::Instance()->getRenderer()
                    );
                
        }
    }
#endif
}

Tileset TileLayer::getTilesetByID(int tileID){
    for (int i = 0; i < m_tilesets.size(); i++){
        if ( i + 1 < m_tilesets.size() -1){
            if(tileID >= m_tilesets[i].firstGridID
            && tileID < m_tilesets[i+1].firstGridID){//[by jim] why???
                return m_tilesets[i];
            }
        } else {
            return m_tilesets[i];
        }
    }

    std::cout << "did not find tileset,return empty tileset" << std::endl;
    Tileset t;
    return t;
}
